package xcmg.device.service.basic;


import com.github.pagehelper.PageInfo;
import yb.ecp.fast.infra.util.PageHelperPlus;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import xcmg.device.dao.entity.PriMaterialsDO;
import xcmg.device.dao.entity.basic.ExcipientBindingInfoDO;
import xcmg.device.dao.mapper.PriMaterialsMapper;
import xcmg.device.dao.mapper.basic.ExcipientBindingInfoMapper;
import xcmg.device.infra.ErrorCode;
import xcmg.device.infra.ExportUtil;
import xcmg.device.service.vo.basic.ExcipientBindingAddVO;
import xcmg.device.service.vo.basic.ExcipientBindingInfoVO;
import xcmg.device.service.vo.basic.ExcipientsInfo;
import xcmg.device.service.vo.basic.ExcipientsReportVo;
import xcmg.device.service.warehouse.CommonService;
import yb.ecp.fast.feign.FastGenClient;
import yb.ecp.fast.infra.infra.ActionResult;
import yb.ecp.fast.infra.infra.PageCommonVO;
import yb.ecp.fast.infra.infra.SearchCommonVO;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author wanghyong
 */
@Service
public class ExcipientBindingInfoService {

    @Autowired
    private ExcipientBindingInfoMapper excipientBindingInfoMapper;

    @Autowired
  private FastGenClient fastGenClient;

  @Autowired
  private PriMaterialsMapper priMaterialsMapper;

  @Autowired
  private CommonService commonService;

  @Autowired
  private HttpServletResponse response;

  public List<ExcipientBindingInfoDO> listByMaterialsNo(String materialsNo, String orgId) {
    return excipientBindingInfoMapper.listByMaterialsNo(materialsNo, orgId);
  }


  public PageCommonVO list(SearchCommonVO<ExcipientBindingInfoVO> condition) {
      PageCommonVO result = new PageCommonVO();
      PageHelperPlus.orderBy("update_time desc,materials_no");
      PageHelperPlus.startPage(condition.getPageNum(), condition.getPageSize());
      List<ExcipientBindingInfoDO> doList = excipientBindingInfoMapper.list(condition.getFilters());
      List<ExcipientBindingInfoVO> voList = new ArrayList<>();
      for (ExcipientBindingInfoDO entity : doList) {
          ExcipientBindingInfoVO model = new ExcipientBindingInfoVO();
          BeanUtils.copyProperties(entity, model);
//      takeDecimals(model);
          voList.add(model);
      }
      result.setPageInfo(new PageInfo(doList));
      result.setPageInfoList(voList);
    return result;
  }


  @Transactional(rollbackFor = Exception.class)
  public ActionResult insert(ExcipientBindingAddVO excipientBindingAddVO, String userId,
      String orgId) {
    String checkResult = checkExcipitBindingParam(excipientBindingAddVO, orgId);
    if (StringUtils.isNotEmpty(checkResult)) {
      return getErrorResult(ErrorCode.Failure, checkResult);
    }
    // 零件信息
    PriMaterialsDO priMaterialsDO = priMaterialsMapper
        .itemByNo(excipientBindingAddVO.getMaterialsNo(), orgId);
    int saveCount = 0;
    for (ExcipientsInfo excipientInfo : excipientBindingAddVO.getExcipients()) {
      saveCount += saveExcipient(priMaterialsDO, excipientInfo, userId);
    }
    return getResult(ErrorCode.Success, String.valueOf(saveCount));
  }

  /**
   * 保存辅料数据
   */
  private Integer saveExcipient(PriMaterialsDO priMaterialsDO, ExcipientsInfo excipientsInfo,
      String userId) {
    // 获取辅料信息
    PriMaterialsDO excipientInfo = priMaterialsMapper
        .itemByNo(excipientsInfo.getExcipientNo(), priMaterialsDO.getOrgId());
    BigDecimal unitPrice =
        null == excipientInfo.getPrice() ? BigDecimal.ZERO : excipientInfo.getPrice();

    ExcipientBindingInfoDO excipientBindingInfoDO = new ExcipientBindingInfoDO();

    ActionResult<String> textResult = fastGenClient.textGuid();
    // 辅料信息
    excipientBindingInfoDO.setExcipientNo(excipientsInfo.getExcipientNo());
    excipientBindingInfoDO.setExcipientPrice(unitPrice);
    excipientBindingInfoDO.setBindingQty(excipientsInfo.getBindingQty());
    excipientBindingInfoDO.setExcipientUnit(excipientInfo.getUnit());
    excipientBindingInfoDO.setExcipientAmount(
        unitPrice.multiply(excipientsInfo.getBindingQty())
            .setScale(2, BigDecimal.ROUND_HALF_UP));
    excipientBindingInfoDO.setExcipientDesc(excipientInfo.getMaterialsDes());
    // 零件信息
    excipientBindingInfoDO.setMaterialsDes(priMaterialsDO.getMaterialsDes());
    excipientBindingInfoDO.setUnit(priMaterialsDO.getUnit());
    excipientBindingInfoDO.setMaterialsNo(priMaterialsDO.getMaterialsNo());

    //运维数据
    excipientBindingInfoDO.setId(textResult.getValue());
    String userName = commonService.getUserName(userId);
    excipientBindingInfoDO.setCreaterId(userId);
    excipientBindingInfoDO.setCreaterName(userName);
    excipientBindingInfoDO.setCreateTime(new Date());
    excipientBindingInfoDO.setUpdateId(userId);
    excipientBindingInfoDO.setUpdateName(userName);
    excipientBindingInfoDO.setUpdateTime(new Date());
    excipientBindingInfoDO.setOrgId(priMaterialsDO.getOrgId());
    return excipientBindingInfoMapper.insert(excipientBindingInfoDO);
  }


  @Transactional(rollbackFor = Exception.class)
  public ActionResult remove(List<String> ids) {
    return getResult(ErrorCode.Success, String.valueOf(excipientBindingInfoMapper.remove(ids)));
  }


  private String checkExcipitBindingParam(ExcipientBindingAddVO excipientBindingAddVO,
      String orgId) {
    if (null == excipientBindingAddVO.getMaterialsNo()) {
      return "零件号不能为空";
    }

    for (ExcipientsInfo excipientInfo : excipientBindingAddVO.getExcipients()) {
      if (null == excipientInfo.getExcipientNo()) {
        return "辅料零件号不能为空";
      }

      if (null == excipientInfo.getBindingQty()) {
        return "绑定数量不能为空";
      }
      List<ExcipientBindingInfoDO> excipientBindingInfoDOS=excipientBindingInfoMapper.listByMaterialsNo(excipientBindingAddVO.getMaterialsNo(),orgId);
      if(excipientBindingInfoDOS.size()>=2){
        return "该零件已经绑定过两种辅料";
      }

      ExcipientBindingInfoDO excipientBindingInfoDB = excipientBindingInfoMapper
          .getByMaterialsAndExcipientNo(excipientBindingAddVO.getMaterialsNo(),
              excipientInfo.getExcipientNo(), orgId);
      if (null != excipientBindingInfoDB) {
        return "该零件对应的辅料绑定关系已存在";
      }
    }

    Integer bindingQty = excipientBindingInfoMapper
        .countByMaterialsNo(excipientBindingAddVO.getMaterialsNo(),
            orgId);
    bindingQty = null == bindingQty ? 0 : bindingQty;

    if (bindingQty >= 2) {
      return "最多允许添加两个辅料";
    }
    return StringUtils.EMPTY;
  }

  private ActionResult getResult(ErrorCode errorCode, String value) {
    return new ActionResult(errorCode.getCode(), errorCode.getDesc(), value);
  }

  private ActionResult getErrorResult(ErrorCode errorCode, String message) {
    return new ActionResult(errorCode.getCode(), message);
  }

  @Transactional(rollbackFor = Exception.class)
  public ActionResult update(ExcipientBindingAddVO excipientBindingAddVO, String userId,
      String orgId) {
    // 删除，添加
    excipientBindingInfoMapper.deleteByMaterialsNo(excipientBindingAddVO.getMaterialsNo(), orgId);
    return insert(excipientBindingAddVO, userId, orgId);
  }


  /**
   * 获取报表数据
   */
  public PageCommonVO listReportData(SearchCommonVO<ExcipientBindingInfoVO> condition) {
      PageCommonVO result = new PageCommonVO();
//    PageHelperPlus.orderBy("materials_no");
      PageHelperPlus.startPage(condition.getPageNum(), condition.getPageSize());
      List<ExcipientsReportVo> doList = excipientBindingInfoMapper
              .listExcipientsData(condition.getFilters());
      result.setPageInfo(new PageInfo(doList));
      result.setPageInfoList(doList);
      return result;
  }

  /**
   * 导出辅料绑定配置
   */
  public void exportAllConfig(ExcipientBindingInfoVO condition) throws Exception {
//    //PageHelperPlus.startPage(0, 0, "create_date desc");
//    List<SaleIntentionVO> voList = new ArrayList<>();
    List<ExcipientBindingInfoDO> doList = excipientBindingInfoMapper.list(condition);

    List<ExcipientBindingInfoVO> voList = new ArrayList<>();
    for (ExcipientBindingInfoDO excipientDO : doList) {

      ExcipientBindingInfoVO excipientBindingInfoVO = new ExcipientBindingInfoVO();
      BeanUtils.copyProperties(excipientDO, excipientBindingInfoVO);
      voList.add(excipientBindingInfoVO);
    }
    invokeConfigExport(voList);
  }

  private void invokeConfigExport(List<ExcipientBindingInfoVO> voList) throws Exception {
    String title = "辅料绑定关系数据导出";
    String[] rowsName = new String[]{"序号", "零件号", "零件名称", "零件单位", "辅料零件号", "辅料零件名称", "辅料单位", "绑定数量",
        "辅料单价", "辅料金额"};
    List<Object[]> dataList = new ArrayList<Object[]>();
    Object[] objs = null;

    if (CollectionUtils.isEmpty(voList)) {
      ExportUtil exportUtil = new ExportUtil(title, rowsName, dataList);
      exportUtil.export(response);
      return;
    }

    for (int i = 0; i < voList.size(); i++) {
      ExcipientBindingInfoVO e = voList.get(i);
      if (e.getExcipientPrice() != null) {
        e.setExcipientPrice(
            e.getExcipientPrice().divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP));
      }
      if (e.getExcipientAmount() != null) {
        e.setExcipientAmount(
            e.getExcipientAmount().divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP));
      }
      objs = new Object[rowsName.length];
      objs[0] = i + 1;
      objs[1] = e.getMaterialsNo();
      objs[2] = e.getMaterialsDes();
      objs[3] = e.getUnit();
      objs[4] = e.getExcipientNo();
      objs[5] = e.getExcipientDesc();
      objs[6] = e.getExcipientUnit();
      objs[7] = formatDecimal(e.getBindingQty());
      objs[8] = formatDecimal(e.getExcipientPrice());
      objs[9] = formatDecimal(e.getExcipientAmount());
      dataList.add(objs);
    }
    ExportUtil exportUtil = new ExportUtil(title, rowsName, dataList);
    exportUtil.export(response);
  }


  /**
   * 导出报表数据
   */
  public void exportAllReport(ExcipientBindingInfoVO condition) throws Exception {
    List<ExcipientsReportVo> voList = excipientBindingInfoMapper.listExcipientsData(condition);
    String title = "辅料报表数据";
    String[] rowsName = new String[]{"序号", "零件号", "零件名称", "零件单位", "未完成订单数量",
        "辅料零件号", "辅料单位", "辅料单价", "总金额", "需求包装数量", "需求金额", "本月实际入库数量",
        "本月实际使用数量", "本月实际使用金额", "本月实际入库时间"};
    List<Object[]> dataList = new ArrayList<Object[]>();
    Object[] objs = null;

    if (CollectionUtils.isEmpty(voList)) {
      ExportUtil exportUtil = new ExportUtil(title, rowsName, dataList);
      exportUtil.export(response);
      return;
    }
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    for (int i = 0; i < voList.size(); i++) {
      ExcipientsReportVo e = voList.get(i);
      objs = new Object[rowsName.length];
      objs[0] = i + 1;
      objs[1] = e.getMaterialsNo();
      objs[2] = e.getMaterialsDes();
      objs[3] = e.getUnit();
      objs[4] = formatDecimal(e.getUndoneMaterialsQty());
      objs[5] = e.getExcipientNo();
      objs[6] = e.getExcipientUnit();
      objs[7] = formatDecimal(e.getTotalAmount());
      objs[8] = formatDecimal(e.getBindingQty());
      objs[9] = formatDecimal(e.getNeededAmount());
      objs[10] = formatDecimal(e.getRealAmount());
      objs[12] = formatDecimal(e.getThisMonthUseQty());
      objs[13] = formatDecimal(e.getThisMonthUseAmount());
      objs[14] = null == e.getThisMonthInboundTime() ? StringUtils.EMPTY
          : format.format(e.getThisMonthInboundTime());
      dataList.add(objs);
    }
    ExportUtil exportUtil = new ExportUtil(title, rowsName, dataList);
    exportUtil.export(response);
  }

  private String formatDecimal(BigDecimal decimal) {
    if (null == decimal) {
      return StringUtils.EMPTY;
    }
    return String.valueOf(decimal);
  }
}


